<?php

namespace App\Http\Controllers;

use App\Http\Resources\LessonResource;
use App\Models\Lesson;
use App\Http\Requests\StoreLessonRequest;
use App\Http\Requests\UpdateLessonRequest;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Request;

class LessonController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:sanctum'])->except(['index']);

    }


    /**
     * @return AnonymousResourceCollection
     */
    public function index(): AnonymousResourceCollection
    {
        return LessonResource::collection(Lesson::latest()->paginate(request('row', 10)));
    }


    /**
     * Store a newly created resource in storage.
     * @param StoreLessonRequest $request
     * @param Lesson $lesson
     * @return array
     * @throws AuthorizationException
     */
    public function store(StoreLessonRequest $request, Lesson $lesson): array
    {
        $this->authorize('create', $lesson);
        $lesson->fill($request->input())->save();
        //添加课程视频
        collect(request('videos'))->map(function ($video) use ($lesson) {
            if (empty($video['path']) || empty($video['title'])) return;
            $lesson->videos()->create($video);
        });
        return $this->success('添加成功', $lesson);
    }

    /**
     * Display the specified resource.
     *
     * @param Lesson $lesson
     * @return LessonResource
     */
    public function show(Lesson $lesson): LessonResource
    {
        return new LessonResource($lesson->load(['videos', 'system']));
        //
    }


    /**
     * Update the specified resource in storage.
     *
     * @param UpdateLessonRequest $request
     * @param Lesson $lesson
     * @return array
     * @throws AuthorizationException
     */
    public function update(UpdateLessonRequest $request, Lesson $lesson): array
    {
        $this->authorize('update', $lesson);
        $lesson->fill($request->input())->save();
        return $this->success('编辑成功', $lesson);
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Lesson $lesson
     * @return array
     * @throws AuthorizationException
     */
    public function destroy(Lesson $lesson): array
    {
        $this->authorize('delete', $lesson);
        $lesson->delete();
        return $this->success('删除成功');
        //
    }
}
